package cn.fl.infside.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.ref.fribaseinfo.transform.FriBaseInfoVOTransform;
import cn.fl.ref.fribaseinfo.utils.FundRasInsNmChangeUtil;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.constant.tripartite.InterfaceConstants;
import cmm.mid.core.framework.dto.MessageDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.infside.transform.InfTransLogVoTransform;
import cn.fl.infside.vo.InfTransLogVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.system.constant.SysLogConstant;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import pam.transmissionrec.facade.api.ITransLogApiService;
import pam.transmissionrec.facade.condition.InfTransLogQueryCondition;
import pam.transmissionrec.facade.dto.InfTransLogDTO;

@Controller
@RequestMapping("/infside/inftranslog")
public class InfTransLogController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InfTransLogController.class);
	
	@Autowired
	private ITransLogApiService transLogApi;
	
	/**
	 * 客户 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	
	@Autowired
	private IFriBaseInfoService friBaseInfoService;//融资机构基础信息表
	
    /**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	/**
	 * 到传输日志接口页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/toInfTransLogList.do", method = { RequestMethod.GET})
	public ModelAndView toInfTransLogList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("infside/inftranslog/infTransLogList");
		// 状态
		List<Map<String,String>> statusList = new ArrayList<Map<String,String>>();
		for(InterfaceConstants.TransStatus status : InterfaceConstants.TransStatus.values()){
			Map<String,String> statusMap = new HashMap<String,String>();
			statusMap.put("key",status.key());
			statusMap.put("value",status.desc());
			statusList.add(statusMap);
		}
		view.addObject("statusList", statusList);
		// 操作动作
		List<Map<String,String>> actionList = new ArrayList<Map<String,String>>();
		for(InterfaceConstants.Action status : InterfaceConstants.Action.values()){
			Map<String,String> actionMap = new HashMap<String,String>();
			actionMap.put("key",status.key());
			actionMap.put("value",status.desc());
			actionList.add(actionMap);
		}
		view.addObject("actionList", actionList);
		// 事业部
		List<KeyValueVO> orgList = cstBscInfoService.searchBusinessOrgList();
		view.addObject("orgListList", orgList);
		view.addObject("currentBuOrgCd",CurrentThreadContext.getCurrentBuOrgCd());

		//业务线字典List
		List<KeyValueVO> bussinessLineDicList = sysDictionaryApiService.getKvList("REF0048","11000","0000");
		// 获取金融机构
		Pager page = new Pager();
		page.setCurrentPage(1);
		page.setEveryPage(Integer.MAX_VALUE);
		FriBaseInfoQueryCondition qc = new FriBaseInfoQueryCondition();
		qc.setInsSts(FriBaseInfoConstant.FRI_BASE_INFO_INS_STS_PASS);
		qc.setInsUseCd("2");
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(qc);
		page = this.friBaseInfoService.searchListPage(page);
		if(null != page){
            List<FriBaseInfoVO> list = FriBaseInfoVOTransform.toVOList((List<FriBaseInfoDTO>) page.getResultList());
            if(null != list){
				//根据金融机构业务线,设置金融机构名称展示字段值
				FundRasInsNmChangeUtil.insNmShowAddBussinessLineDic(list,bussinessLineDicList);
				view.addObject("fundRasInsList", list);
			}
		}
		BaseLogUtils.info(logger, "toInfTransLogList", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/queryInfTransLogList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object queryInfTransLogList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String status = request.getParameter("status");//状态
		String lsCntNo = request.getParameter("lsCntNo");//合同号
		String paySchNo = request.getParameter("paySchNo");//支付表编号
		String cstNm = request.getParameter("cstNm");//承租人
		String certNo = request.getParameter("certNo");//身份证号
		String buOrgCd = request.getParameter("buOrgCd");//所属事业部
		String fundRasInsId = request.getParameter("fundRasInsId");//金融机构
		String action = request.getParameter("action");//操作动作
        //是否删除
        String isDel = request.getParameter("isDel");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		InfTransLogQueryCondition condition = new InfTransLogQueryCondition();
		if (StringUtils.isNotEmpty(status)) {
			condition.setStatus(status);
		}
		if (StringUtils.isNotEmpty(lsCntNo)) {
			condition.setLsCntNo(lsCntNo);
		}
		if (StringUtils.isNotEmpty(paySchNo)) {
			condition.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotEmpty(cstNm)) {
			condition.setCstNm(cstNm);
		}
		if (StringUtils.isNotEmpty(buOrgCd)) {
			condition.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotEmpty(fundRasInsId)) {
			condition.setFundRasInsId(Long.parseLong(fundRasInsId));
		}
		if (StringUtils.isNotEmpty(action)) {
			condition.setAction(action);
		}
		if (StringUtils.isNotEmpty(certNo)) {
			condition.setRespCode(certNo);
		}
		if (StringUtils.isNotEmpty(isDel)) {
			condition.setIsDel(Integer.parseInt(isDel));
		}
		page.setCondition(condition);
		Pager pager = transLogApi.findTransLogsByPager(page);
		logger.info("三方日志查询到的结果：" + JSONObject.toJSONString(pager));
		List<InfTransLogVO> vos = InfTransLogVoTransform.toVoList((List<InfTransLogDTO>) pager.getResultList());
        logger.info("转换后结果：" + JSONObject.toJSONString(vos));
		if(null != vos){
			List<KeyValueVO> orgList = cstBscInfoService.searchBusinessOrgList();
			List<SysDictionaryDTO> dics = sysDictionaryApiService.searchGroup("11000", "0000", "INF0003");
			InterfaceConstants.TransStatus statusEnum;
			InterfaceConstants.Action actionEnum;
			String insCode;
			String dicParentCode;
			String dicCode;
			String dicCodeAttr1;
			Integer oleIsDel;
			for(InfTransLogVO vo : vos){
				// 处理状态
				if(StringUtils.isNotEmpty(vo.getStatus())){
					try {
						statusEnum = InterfaceConstants.TransStatus.valueOf(vo.getStatus());
						if(null != statusEnum){
							vo.setStatusDesc(statusEnum.desc());
						}
					} catch (Exception e) {
					}
				}
				// 处理动作
				action = vo.getAction();
				if(StringUtils.isNotEmpty(action)){
					try {
						actionEnum = InterfaceConstants.Action.valueOf(action);
						if(null != actionEnum){
							vo.setActionDesc(actionEnum.desc());
						}
					} catch (Exception e) {
					}
				}
				// 处理事业部
				if(StringUtils.isNotBlank(vo.getBuOrgCd())){
					if(null != orgList){
						for(KeyValueVO kv : orgList){
							if(vo.getBuOrgCd().equals(kv.getKey())){
								vo.setBuOrgNm(kv.getValue());
								break;
							}
						}
					}
				}
                // 处理是否删除
                oleIsDel = vo.getIsDel();
                if(StringUtils.isNotBlank(oleIsDel==null?"":oleIsDel+"")){
                    if (0 == oleIsDel) {
                        vo.setIsDelDesc("否");
                    } else if (1 == oleIsDel) {
                        vo.setIsDelDesc("是");
                    } else {
                        vo.setIsDelDesc("未知");
                    }
                }
				// 处理操作权限
				insCode = vo.getFundRasInsNo();
				if(StringUtils.isNotBlank(insCode) && StringUtils.isNotBlank(action) ){
					if(null != dics){
						for(SysDictionaryDTO dic : dics){
							dicParentCode = dic.getPCode();
							dicCode = dic.getCode();
							dicCodeAttr1 = dic.getCodeAttr1();
							if(insCode.equals(dicParentCode) && action.equals(dicCode)
									&& "1".equals(dicCodeAttr1)){
								vo.setDisplayButton(1);
								break;
							}
						}
					}
				}
			}
		}
		ListPageVO<InfTransLogVO> listPage = new ListPageVO<InfTransLogVO>(vos, pager.getTotalCount());
		BaseLogUtils.info(logger, "queryInfTransLogList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	@RequestMapping(value = "/modifyLog.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object modifyLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作完成");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modifyLog", "参数空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			InfTransLogDTO dto = new InfTransLogDTO();
			dto.setId(Long.parseLong(id));
			dto.setIsDel(1);
			MessageDTO<String> messageDto = transLogApi.updateTransLog(dto);
			if (!messageDto.isSuccess()) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("作废失败");
				BaseLogUtils.info(logger, "changePayStatus", "作废失败", CurrentThreadContext.getCurrentUserName());
			}
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("作废失败！");
			logger.error("作废失败！", ex);
		}
		return result;
	}
	
}
